package com.gl.sass.mq.message;

import com.alibaba.fastjson.JSON;

import lombok.Getter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.common.message.MessageExt;

/**
 * 
 * @author xiehong
 *
 */
@Getter
public class BaseMessage {

    /**
     * 2个小时
     */
    private static final long MSG_VALID_TIME = 2 * 60 * 60 * 1000;

    private List<MessageExt> msgs;

    private ConsumeConcurrentlyContext context;

    private String firstTags;

    private String firstMsgId;

    private String firstBody;

    private long storeTimestamp;

    private int reconsumeTimes;

    public BaseMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
        this.msgs = msgs;
        this.context = context;

        init();
    }

    public void init() {
        setFirstTags();
        setFirstMsgId();
        setFirstBody();
        setStoreTimestamp();
        setReconsumeTimes();
    }

    private void setReconsumeTimes() {
        this.reconsumeTimes = msgs.isEmpty() ? 0 : msgs.get(0).getReconsumeTimes();
    }

    private void setFirstTags() {
        this.firstTags = msgs.isEmpty() ? null : msgs.get(0).getTags();
    }

    private void setFirstMsgId() {
        this.firstMsgId = msgs.isEmpty() ? null : msgs.get(0).getMsgId();
    }

    private void setStoreTimestamp() {
        this.storeTimestamp = msgs.isEmpty() ? 0 : msgs.get(0).getStoreTimestamp();
    }

    private void setFirstBody() {
        this.firstBody = msgs.isEmpty() ? null : new String(msgs.get(0).getBody());
    }

    public <T> T getFirstObject(Class<T> clazz) {
        return Optional.ofNullable(getFirstBody()).map(o -> JSON.parseObject(o, clazz)).orElse(null);
    }

    public <T> List<T> getfirstArray(Class<T> clazz) {
        return Optional.ofNullable(getFirstBody()).map(o -> JSON.parseArray(o, clazz)).orElse(null);
    }

    public boolean isMsgInValid(Long milltims) {
        return System.currentTimeMillis() - storeTimestamp > milltims;
    }

    public boolean isMsgInValid() {
        return isMsgInValid(MSG_VALID_TIME);
    }

    public String getStoreTimestamp() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss”").format(new Date(storeTimestamp));
    }
}
